// pages/order/order.js
let {fetchdetailedMovie} = require('../../api/index.js')
const {fetchGetOpenid,fetchPayOrder,fetchUserOrder} = require('../../api/user.js')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        orderList:[]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        let {data} = await fetchUserOrder()
        let promiseArr = data.map(item => {
            return fetchdetailedMovie(item.movieid)
        })
        let result = await Promise.all(promiseArr)
        result = result.map((item,index) => {
            item.data.movie.status = data[index].status;
            item.data.movie.orderid = data[index].orderid;
            item.data.movie.img = item.data.movie.img.replace(/\/w\.h/,'')
            return item.data.movie;
        })
        this.setData({
            orderList:result
        })
    },
    // 下订单
    async payHandle(movieid){
        // 先获取openid
       let openid = wx.getStorageSync('openid')
        if(!openid){
            // 直接进入到要授权的页面
            wx.navigateTo({
              url: '/pages/login/login',
            })
            return;
        }
        // 在调用支付接口 传递 openid,movieid,获取预支付参数
        try {
            let prepayData = await fetchPayOrder(movieid,openid);
            if(prepayData.errcode !== 200){
                wx.showToast({
                  title: prepayData.message,
                })
                return;
            }
            let {nonce_str,mypackage,sign_type,paySign,timeStamp} = prepayData.result.xml;
            // 调用wxwx.requestPayment拉起微信支付
            wx.requestPayment({
                nonceStr: nonce_str,
                package: mypackage,
                signType: sign_type,
                paySign: paySign,
                timeStamp: timeStamp,
                complete(){
                    wx.redirectTo({
                      url: '/pages/order/order',
                    })
                },
            })
        }catch(err){
            console.log('error message:',err.message)
        }
        
    },

    pay(event){
        let {movieid} = event.detail
        this.payHandle(movieid);
       
    }
})